<?php

/**
 * Created by PhpStorm.
 * User: d7
 * Date: 2016/1/23
 * Time: 10:47
 */
class Helper extends MY_View_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('Helper_model');
        $config = $this->config->load('redis');
        $this->load->library('redis_session_relation',$config);
    }

    function login(){
        $account = $this->input->post('account');
        $password = $this->input->post('password');
        $helper=$this->Helper_model->get(array('account'=>$account,'password'=>$password),1);
        if($helper){
            unset($helper['password']);
            $_SESSION['login_helper'] = $helper;
            $helper['busy'] = 0;
            $this->redis_session_relation->set_helpers($helper['_id'],$helper);
            $this->json_response(true,array('url'=>'http://helper.paintmore.cn/helper/'.$helper['_id']));
        }
        $this->json_response(false);
    }

    function set_busy(){
        $busy = $this->input->post('busy');
        $helper_id = $this->input->post('id');
        $helper = $this->redis_session_relation->get_helper($helper_id);
        $helper['busy'] = $busy;

        if(!$this->redis_session_relation->set_helpers($helper_id,$helper)){
            $this->json_response(false);
        }
        $this->json_response(true);
    }

    function get_helper(){
        $helpers = $this->redis_session_relation->get_helper();
        $helper = $this->randHelper($helpers);
        if(empty($helper)){
            $this->json_response(false);
        }
        $this->json_response(true,$helper);
    }

    private function randHelper($helpers)
    {
        if(count($helpers) > 0){
            $rand = rand(0,$helpers);
        }else{
            return null;
        }
        if($helpers[$rand]['busy']!=0){
            $this->randHelper($helpers);
        }
        $helper['busy']=1;
        $this->redis_session_relation->set_helpers($helper['_id'],$helper);
        return $helper;
    }
}